package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.service.WechatService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author: ZHD
 * @Date: 2025/08/20 10:42
 * @Description:
 */
@Service
public class WechatServiceImpl implements WechatService {

    // 微信请求地址
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;

    @Override
    public String getOpenid(String code) {
        try {
            HashMap<String, Object> params = getAppIdAndSecret();
            params.put("js_code", code);
            String result = HttpUtil.get(REQUEST_URL, params);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if (ObjUtil.isNotEmpty(jsonObject.getInt("errcode"))){
                throw new BaseException("获取openid失败", jsonObject.getStr("errmsg"));
            }
            return result;
        } catch (BaseException e) {
            throw new BaseException("网络繁忙,请稍后重试",e.getMessage());
        }
    }



    @Override
    public String getPhone(String code) {
        try {
            HashMap<String, Object> params = new HashMap<>();
            params.put("code", code);
            String result = HttpUtil.post(PHONE_REQUEST_URL + getToken(), JSONUtil.toJsonStr(params));
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if(jsonObject.getInt("errcode") != 0){
                throw new BaseException("获取手机号失败", jsonObject.getStr("errmsg"));
            }
            return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
        } catch (BaseException e) {
            throw new BaseException("网络繁忙,请稍后重试",e.getMessage());
        }
    }

    @Override
    public String getToken() {
        try {
            HashMap<String, Object> params = getAppIdAndSecret();
            String result = HttpUtil.get(TOKEN_URL, params);
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String accessToken = jsonObject.getStr("access_token");
            if ((StringUtils.isEmpty(accessToken))){
                throw new BaseException("获取token失败", jsonObject.getStr("errmsg"));
            }
            return accessToken;
        } catch (BaseException e) {
            throw new BaseException("网络繁忙,请稍后重试",e.getMessage());
        }
    }

    private @NotNull HashMap<String, Object> getAppIdAndSecret() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        return params;
    }
}
